import { createContext, useContext } from 'react'
import { action, computed, makeObservable, observable } from 'mobx'

class AppleStore {
  apples = [{ id: 0, weight: 233, isEaten: false }]
  isPicking = false
  buttonText = '摘苹果'
  newAppleId = 1
  constructor() {
    makeObservable(this, {
      apples: observable,
      isPicking: observable,
      buttonText: observable,
      eatApple: action.bound,
      pickApple: action.bound,
      status: computed,
    })
  }

  eatApple(id) {
    const target = this.apples.find(apple => apple.id === id)
    target.isEaten = true
  }

  get status() {
    let status = {
      appleNow: {
        quantity: 0,
        weight: 0
      },
      appleEaten: {
        quantity: 0,
        weight: 0
      }
    }
    this.apples.forEach(apple => {
      let selector = apple.isEaten ? 'appleEaten' : 'appleNow'
      status[selector].quantity++
      status[selector].weight += apple.weight
    })
    return status
  }

  pickApple() {
    if (this.isPicking) {
      return
    }

    this.isPicking = true
    this.buttonText = '正在采摘...'
    fetch('https://hacker-news.firebaseio.com/v0/jobstories.json').then(res => {
      /** 备注这里的url只是测试用的，这个是之前hackernews的api, 这里只是确保接口是通的，至于数据还是自己mock */
      let weight = Math.floor(200 + Math.random() * 50)
      this.isPicking = false
      this.buttonText = '摘苹果'
      this.apples.push({
        id: this.newAppleId++,
        weight: weight,
        isEaten: false
      })
    })
  }
}

const AppleContext = createContext()

const AppleStoreProvide = ({ store, children }) => {
  return <AppleContext.Provider value={store}>{children}</AppleContext.Provider>
}

const useAppleStore = () => useContext(AppleContext)

export { AppleStore, AppleStoreProvide, useAppleStore }
